import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { useUserStore } from "./userStore.js"
import { insertCartAPI, findNewCartListAPI, delCartAPI } from "@/apis/cart.js";
//两个组件调用一个数据 调用一次
export const useCartStore = defineStore('cart', () => {
    const userStore = useUserStore()
    const isLogin = computed(() => userStore.userInfo.token)
    //定义state -cartList
    let cartList = ref([]);
    // 获取最新的购物车数据
    const updateNewList = async () => {
        const res = await findNewCartListAPI()
        cartList.value = res.result
    }
    //获取数据
    const addCart = async (goods) => {
        const { count, skuId } = goods
        if (isLogin.value) {
            await insertCartAPI({ count, skuId })
            updateNewList()
        } else {
            //  添加过 count+1  
            //没添加过直接push
            // /通过匹配传递的商品数据中的skuid能不能在cartlist中找到就是添加过
            const item = cartList.value.find((item) => goods.skuId === item.skuId)
            if (item) {
                //找到了
                item.count++
            } else {
                //没找到
                cartList.value.push(goods)
            }
        }

    };
    //删除购物车数据
    const delCart = async (skuId) => {
        // console.log(skuId);
        if (isLogin.value) {
            //有token的逻辑 调用删除接口
            await delCartAPI([skuId])
            updateNewList()
        } else {
            // 1找到删除项的下标值 splice
            const dex = cartList.value.findIndex((item) => skuId === item.skuId)
            cartList.value.splice(dex, 1)
            // 2使用数组的过滤方法 filter 
            // const dex = cartList.value.filter((item) => skuId === item.skuId)
            // cartList = dex
        }
    }
    //清除购物车
    const clearCart = () => {
        cartList.value = []
    }
    // 计算属性
    //1总的数量 count之和
    const countCart = computed(() => cartList.value.reduce((a, c) => c.count + a, 0));
    // 总价 price
    const priceCart = computed(() => cartList.value.reduce((a, c) => c.price * c.count + a, 0))
    //单选
    const singleCheck = (skuId, selected) => {
        const item = cartList.value.find((item) => item.skuId == skuId)
        item.selected = selected
    }
    //全选
    const allCheck = (selected) => {
        cartList.value.forEach(item => item.selected = selected)
    }
    //是否全选
    const isAll = computed(() => cartList.value.every(item => item.selected))
    //以选择数量
    const selectedCount = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => c.count + a, 0))
    //选择的价钱
    const selectedPrice = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => c.price * c.count + a, 0))
    //商品合计
    return {
        cartList, addCart, delCart, countCart, priceCart, clearCart, singleCheck, isAll, allCheck, selectedCount, selectedPrice, updateNewList
    }

}, { persist: true })
